<template>
  <div class="dashboard-container">
    <!-- 页面标题和统计信息 -->
    <div class="dashboard-header">
      <div class="left-section">
        <h1 class="main-title">
          <span class="greeting">{{ greeting }}</span>
          <span class="platform-name">欢迎访问舟山大桥综管指挥平台</span>
        </h1>
        <p class="subtitle">
          <span class="subtitle-item">实时监控</span>
          <span class="subtitle-separator">|</span>
          <span class="subtitle-item">预警分析</span>
          <span class="subtitle-separator">|</span>
          <span class="subtitle-item">智能管理</span>
        </p>
      </div>
      <div class="right-section">
        <div class="current-time"><el-icon>
            <Clock />
          </el-icon> {{ currentTime }}</div>
        <!-- <div class="user-info" @click="showUserMenu = !showUserMenu">
          <div class="avatar-wrapper">
            <el-icon class="avatar-icon">
              <User />
            </el-icon>
          </div>
          <span>管理员</span>
          <el-icon class="expand-icon">
            <ArrowDown />
          </el-icon>
          <div v-if="showUserMenu" class="user-menu">
            <div class="user-menu-item"><el-icon>
                <UserFilled />
              </el-icon> 个人中心</div>
            <div class="user-menu-item"><el-icon>
                <Setting />
              </el-icon> 设置</div>
            <div class="user-menu-item"><el-icon>
                <SwitchButton />
              </el-icon> 退出登录</div>
          </div>
        </div> -->
      </div>
    </div>

    <!-- 统计卡片栏 -->
    <div class="stats-cards">
      <transition-group name="stats-fade">
        <div v-for="(stat, index) in statsItems" :key="index" class="stat-card"
          :class="{ 'pulse-animation': stat.showPulse }" @mouseenter="onStatHover(index)"
          @mouseleave="onStatLeave(index)">
          <div class="stat-header">
            <div class="stat-title">{{ stat.title }}</div>
            <el-icon class="stat-icon" :class="stat.iconColor">
              <component :is="stat.icon" />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">
              <count-to :start-val="0" :end-val="Number(stat.value.replace(/,/g, ''))" :duration="2000" :separator="','"
                :decimal="0" :autoplay="true"></count-to>
            </div>
            <div class="stat-trend">
              <span>总计</span>
              <span class="trend-up">
                <el-icon class="trend-icon">
                  <ArrowUp />
                </el-icon>
                {{ stat.trend }}
              </span>
            </div>
          </div>
        </div>
      </transition-group>
    </div>

    <!-- 模块卡片栏 -->
    <div class="module-cards" style="display: flex;">
      <div class="module-row" style="display: flex;">
        <div style="width: 49%;">
          <div class="module-title">
            <el-icon>
              <Connection />
            </el-icon>
            <span>我的动态</span>
          </div>
          <div class="modules-container">
            <div v-for="(item, index) in myModules" :key="index" class="module-item" @click="handleModuleClick(item)"
              :style="{ animationDelay: `${index * 0.1}s` }">
              <el-icon class="module-icon" :class="item.color">
                <component :is="item.icon" />
              </el-icon>
              <div class="module-name">{{ item.name }}</div>
              <div v-if="item.badge" class="module-badge">{{ item.badge }}</div>
            </div>
          </div>
        </div>
        <div style="width: 49%;">
          <div>
            <div class="module-title">
              <el-icon>
                <Menu />
              </el-icon>
              <span>平台功能</span>
            </div>
            <div class="modules-container">
              <div v-for="(item, index) in platformModules" :key="index" class="module-item"
                @click="navigateTo(item.route)" :style="{ animationDelay: `${index * 0.1}s` }">
                <el-icon class="module-icon" :class="item.color">
                  <component :is="item.icon" />
                </el-icon>
                <div class="module-name">{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>


    </div>

    <!-- 内容主体 -->
    <div class="dashboard-content">
      <!-- 左侧: 桥梁健康和传感器状态 -->
      <div class="content-column">
        <div class="content-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon>
                <TrendCharts />
              </el-icon>
              <span>桥梁健康监测</span>
            </div>
            <div class="card-actions">
              <el-radio-group v-model="healthViewMode" size="small">
                <el-radio-button label="progress">进度条</el-radio-button>
                <el-radio-button label="chart">图表</el-radio-button>
              </el-radio-group>
              <el-button type="primary" size="small" @click="navigateTo('/health-monitor')">
                查看详情
              </el-button>
            </div>
          </div>
          <div class="card-content">
            <div v-if="healthViewMode === 'progress'" class="health-indicators">
              <div v-for="(component, index) in healthComponents" :key="index" class="health-component"
                @mouseenter="component.hover = true" @mouseleave="component.hover = false">
                <div class="component-info">
                  <div class="component-name">{{ component.name }}</div>
                  <div class="component-score" :class="getHealthScoreClass(component.score)">
                    {{ component.score }}分
                  </div>
                </div>
                <el-progress :percentage="component.score" :color="getHealthColor(component.score)" :format="() => ''"
                  :stroke-width="component.hover ? 12 : 10" class="health-progress" />
              </div>
            </div>
            <div v-else class="health-chart">
              <div id="healthChart" class="chart-container"></div>
            </div>
          </div>
        </div>

        <div class="content-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon>
                <Warning />
              </el-icon>
              <span>预警信息</span>
              <el-badge :value="warningList.length" :max="99" class="warning-badge" type="danger" />
            </div>
            <div class="card-actions">
              <el-button-group>
                <el-button size="small" :type="warningFilter === 'all' ? 'primary' : 'default'"
                  @click="warningFilter = 'all'">
                  全部
                </el-button>
                <el-button size="small" :type="warningFilter === 'high' ? 'primary' : 'default'"
                  @click="warningFilter = 'high'">
                  高危
                </el-button>
                <el-button size="small" :type="warningFilter === 'unhandled' ? 'primary' : 'default'"
                  @click="warningFilter = 'unhandled'">
                  未处理
                </el-button>
              </el-button-group>
              <el-button type="primary" size="small" @click="navigateTo('/warnings')">
                查看全部
              </el-button>
            </div>
          </div>
          <div class="card-content">
            <el-table :data="filteredWarnings" style="width: 100%" size="small" :row-class-name="warningRowClassName"
              @row-click="handleWarningClick">
              <el-table-column prop="title" label="预警信息" min-width="180">
                <template #default="scope">
                  <div class="warning-title">
                    <el-icon v-if="scope.row.level === 'high'" class="pulse-icon">
                      <WarningFilled />
                    </el-icon>
                    {{ scope.row.title }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="类型" width="100" />
              <el-table-column prop="level" label="级别" width="80">
                <template #default="scope">
                  <el-tag :type="getWarningLevelType(scope.row.level)" size="small" effect="dark">
                    {{ getWarningLevelText(scope.row.level) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="时间" width="160">
                <template #default="scope">
                  {{ formatTime(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          
        </div>
            <!-- 知识库和帮助区域 -->
    <div class="knowledge-section">
      <div class="section-header">
        <h2 class="section-title">
          <el-icon>
            <Reading />
          </el-icon>
          学习资源
        </h2>
        <el-button type="primary" size="small" plain @click="navigateTo('/knowledge')">
          查看更多
        </el-button>
      </div>

      <div class="knowledge-items">
        <div v-for="(item, index) in knowledgeItems" :key="index" class="knowledge-item"
          @click="viewKnowledgeItem(item)">
          <div class="knowledge-icon">
            <el-icon>
              <component :is="item.icon" />
            </el-icon>
          </div>
          <div class="knowledge-content">
            <h3 class="knowledge-title">{{ item.title }}</h3>
            <p class="knowledge-desc">{{ item.description }}</p>
          </div>
        </div>
      </div>
    </div>
      </div>

      <!-- 右侧: 设备状态和天气信息 -->
      <div class="content-column">
        <div class="content-card weather-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon>
                <Sunny />
              </el-icon>
              <span>天气情况</span>
            </div>
            <el-button size="small" text @click="refreshWeather">
              <el-icon>
                <Refresh />
              </el-icon>
              刷新
            </el-button>
          </div>
          <div class="card-content weather-content">
            <div class="current-weather">
              <div class="weather-location-section">
                <el-icon class="location-icon">
                  <Location />
                </el-icon>
                <span class="weather-location">{{ weatherData.location }}</span>
              </div>
              <div class="weather-main">
                <div class="weather-icon-temp">
                  <div class="weather-icon">
                    <el-icon>
                      <component :is="getWeatherIcon(weatherData.current.condition)" />
                    </el-icon>
                  </div>
                  <div class="weather-temp">{{ weatherData.current.temperature }}<span>°C</span></div>
                </div>
                <div class="weather-condition-details">
                  <div class="weather-cond">{{ getWeatherConditionText(weatherData.current.condition) }}</div>
                  <div class="weather-details">
                    <div class="weather-detail">
                      <el-icon>
                        <WindPower />
                      </el-icon>
                      <span class="detail-label">风向:</span>
                      <span class="detail-value">{{ weatherData.current.windDirection }}</span>
                    </div>
                    <div class="weather-detail">
                      <el-icon>
                        <Odometer />
                      </el-icon>
                      <span class="detail-label">风速:</span>
                      <span class="detail-value">{{ weatherData.current.windSpeed }}km/h</span>
                    </div>
                    <div class="weather-detail">
                      <el-icon>
                        <Watermelon />
                      </el-icon>
                      <span class="detail-label">湿度:</span>
                      <span class="detail-value">{{ weatherData.current.humidity }}%</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="weather-forecast">
              <div v-for="(day, index) in weatherData.forecast" :key="index" class="forecast-day">
                <div class="forecast-date">{{ day.date }}</div>
                <div class="forecast-icon">
                  <el-icon>
                    <component :is="getWeatherIcon(day.condition)" />
                  </el-icon>
                </div>
                <div class="forecast-temp">
                  <span class="temp-max">{{ day.tempMax }}°</span>
                  <span class="temp-min">{{ day.tempMin }}°</span>
                </div>
                <div class="forecast-wind">
                  <el-icon>
                    <WindPower />
                  </el-icon>
                  {{ day.windSpeed }}km/h
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon>
                <Monitor />
              </el-icon>
              <span>设备状态</span>
            </div>
            <el-button type="primary" size="small" @click="navigateTo('/device-management')">
              管理设备
            </el-button>
          </div>
          <div class="card-content">
            <div class="device-overview">
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="device-stat total" @click="showDeviceTypeInfo('total')">
                    <div class="device-stat-icon">
                      <el-icon>
                        <List />
                      </el-icon>
                    </div>
                    <div class="stat-number">
                      <count-to :start-val="0" :end-val="sensorData.total" :duration="2000" :autoplay="true"></count-to>
                    </div>
                    <div class="stat-name">总数</div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="device-stat online" @click="showDeviceTypeInfo('online')">
                    <div class="device-stat-icon">
                      <el-icon>
                        <Check />
                      </el-icon>
                    </div>
                    <div class="stat-number">
                      <count-to :start-val="0" :end-val="sensorData.online" :duration="2000"
                        :autoplay="true"></count-to>
                    </div>
                    <div class="stat-name">在线</div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="device-stat offline" @click="showDeviceTypeInfo('offline')">
                    <div class="device-stat-icon">
                      <el-icon>
                        <CircleClose />
                      </el-icon>
                    </div>
                    <div class="stat-number">{{ sensorData.offline }}</div>
                    <div class="stat-name">离线</div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="device-stat warning" @click="showDeviceTypeInfo('warning')">
                    <div class="device-stat-icon">
                      <el-icon>
                        <WarningFilled />
                      </el-icon>
                    </div>
                    <div class="stat-number">{{ sensorData.warning }}</div>
                    <div class="stat-name">异常</div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="sensor-categories">
              <div v-for="(category, index) in sensorData.categories" :key="index" class="sensor-category"
                @mouseenter="category.hover = true" @mouseleave="category.hover = false">
                <div class="category-header">
                  <div class="category-name">{{ category.name }}</div>
                  <div class="category-stats-text">
                    <span class="online-count">{{ category.online }}</span>
                    <span class="separator">/</span>
                    <span class="total-count">{{ category.total }}</span>
                  </div>
                </div>
                <div class="category-progress-wrapper">
                  <el-progress :percentage="Math.round((category.online / category.total) * 100)" :format="() => ''"
                    :stroke-width="category.hover ? 10 : 8" class="category-progress" />
                </div>
              </div>
            </div>
          </div>
        </div>

        
      </div>
    </div>



    <!-- 设备详情弹窗 -->
    <el-dialog v-model="deviceDialog.visible" :title="deviceDialog.title" width="50%" destroy-on-close>
      <div class="device-dialog-content">
        <div class="device-dialog-summary">
          <div class="summary-item">
            <div class="summary-label">设备总数</div>
            <div class="summary-value">{{ deviceDialog.data.count }}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">状态</div>
            <div class="summary-value">{{ deviceDialog.data.status }}</div>
          </div>
          <div class="summary-item">
            <div class="summary-label">最近更新</div>
            <div class="summary-value">{{ deviceDialog.data.lastUpdate }}</div>
          </div>
        </div>
        <el-table :data="deviceDialog.data.items" style="width: 100%" size="small">
          <el-table-column prop="id" label="设备ID" width="100" />
          <el-table-column prop="name" label="设备名称" min-width="150" />
          <el-table-column prop="type" label="设备类型" width="120" />
          <el-table-column prop="location" label="位置" min-width="150" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '在线' ? 'success' : (scope.row.status === '异常' ? 'danger' : 'info')"
                size="small">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deviceDialog.visible = false">关闭</el-button>
          <el-button type="primary" @click="navigateTo('/device-management')">
            管理设备
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预警详情弹窗 -->
    <el-dialog v-model="warningDialog.visible" :title="warningDialog.title" width="50%" destroy-on-close>
      <div class="warning-dialog-content">
        <div class="warning-info">
          <div class="warning-info-item">
            <span class="warning-info-label">预警ID:</span>
            <span class="warning-info-value">{{ warningDialog.data.id }}</span>
          </div>
          <div class="warning-info-item">
            <span class="warning-info-label">类型:</span>
            <span class="warning-info-value">{{ warningDialog.data.type }}</span>
          </div>
          <div class="warning-info-item">
            <span class="warning-info-label">级别:</span>
            <span class="warning-info-value">
              <el-tag :type="getWarningLevelType(warningDialog.data.level || '')" size="small" effect="dark">
                {{ getWarningLevelText(warningDialog.data.level || '') }}
              </el-tag>
            </span>
          </div>
          <div class="warning-info-item">
            <span class="warning-info-label">时间:</span>
            <span class="warning-info-value">{{ formatTime(warningDialog.data.createTime || '') }}</span>
          </div>
          <div class="warning-info-item">
            <span class="warning-info-label">状态:</span>
            <span class="warning-info-value">
              <el-tag :type="warningDialog.data.status === '处理中' ? 'warning' : 'danger'" size="small">
                {{ warningDialog.data.status }}
              </el-tag>
            </span>
          </div>
        </div>
        <div class="warning-content">
          <div class="warning-content-label">详细信息:</div>
          <div class="warning-content-value">{{ warningDialog.data.content }}</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warningDialog.visible = false">关闭</el-button>
          <el-button type="warning" @click="handleWarningMark(warningDialog.data)">
            标记为处理中
          </el-button>
          <el-button type="success" @click="handleWarningSolve(warningDialog.data)">
            标记为已解决
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, reactive, watchEffect, nextTick } from 'vue';
import {
  Warning,
  WarningFilled,
  Monitor,
  DataAnalysis,
  Setting,
  TrendCharts,
  Document,
  Van,
  Notification,
  More,
  Sunny,
  Cloudy,
  Lightning,
  User,
  UserFilled,
  ArrowUp,
  ArrowDown,
  View,
  Download,
  Upload,
  ChatLineRound,
  Star,
  Reading,
  Bell,
  Connection,
  OfficeBuilding,
  VideoPlay,
  Notebook,
  Clock,
  Menu,
  List,
  Check,
  CircleClose,
  Refresh,
  Location,
  WindPower,
  Odometer,
  Watermelon,
  SwitchButton,
  Ship
} from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts/core';
import { BarChart, PieChart, LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import CountTo from 'vue-count-to';
import {
  getDashboardStats,
  getPlatformItems,
  getKnowledgeItems,
  getBridgeHealthStatus,
  getSensorStatus,
  getWeatherData,
  DashboardStats,
  PlatformItem as PlatformItemType,
  KnowledgeItem as KnowledgeItemType
} from '@/api/dashboard';
import { getNoticeList } from '@/api/bridge/command/notice';
import { 
  getTrafficAccidentWarningList 
} from '@/api/bridge/traffic/traffic';
import { 
  getEnvironmentalPollutionWarningList 
} from '@/api/bridge/traffic/environmental';
import { 
  getGeologyWarningList 
} from '@/api/bridge/traffic/geology';
import { 
  getPublicHealthWarningList 
} from '@/api/bridge/traffic/publicHealth';
import { 
  getMeteorologicalWarningList 
} from '@/api/bridge/traffic/weather';
import { 
  getShipWarningList 
} from '@/api/bridge/traffic/ship';
import { 
  getEmergencyEventList 
} from '@/api/bridge/command/event';

// Register ECharts components
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  PieChart,
  LineChart,
  CanvasRenderer
]);

const router = useRouter();

// 问候语和当前时间
const currentTime = ref<string>('');
const greeting = computed(() => {
  const hour = new Date().getHours();
  if (hour < 12) return '早上好！';
  if (hour < 18) return '下午好！';
  return '晚上好！';
});

// 用户菜单
const showUserMenu = ref(false);

// 更新当前时间
function updateCurrentTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  currentTime.value = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
}

// 数据加载状态
const loading = ref(false);

// 统计卡片数据
const statsItems = ref([
  {
    title: '总预警数量',
    value: '59',
    trend: '16.7%',
    icon: 'Warning',
    iconColor: 'text-red-500',
    showPulse: false
  },
  {
    title: '事件数量',
    value: '12,032',
    trend: '20.9%',
    icon: 'DataAnalysis',
    iconColor: 'text-blue-500',
    showPulse: false
  },
  {
    title: '通知数量',
    value: '23,032',
    trend: '12.3%',
    icon: 'Bell',
    iconColor: 'text-orange-500',
    showPulse: false
  },
  {
    title: '处置数量',
    value: '32,100',
    trend: '40.8%',
    icon: 'Check',
    iconColor: 'text-green-500',
    showPulse: false
  }
]);

// 模块项目
const myModules = ref([
  { name: '消息中心', icon: 'ChatLineRound', color: 'blue', badge: 0, route: '/notice/noticeyj' },
  { name: '预警信息', icon: 'Star', color: 'yellow', badge: 0, route: '/early-warning/information' },
  { name: '事件管理', icon: 'Reading', color: 'green', badge: 0, route: '/monitor/event' },
  { name: '工作总结', icon: 'Bell', color: 'red', badge: null, route: '/monitor/work' }
]);

const platformModules = ref([
  { name: '应急资源', icon: 'Monitor', color: 'cyan', route: '/monitor/emergency-resources' },
  { name: '桥梁数据', icon: 'Connection', color: 'purple', route: '/basic-data/bridge' },
  { name: '船舶数据', icon: 'Ship', color: 'orange', route: '/system/management' },
  { name: '电子围栏', icon: 'Location', color: 'red', route: '/hnfd/test_01' }
]);

// 统计数据
const statistics = ref<DashboardStats>({
  bridgeHealth: 0,
  warningCount: 0,
  deviceTotal: 0,
  maintenanceCount: 0,
  trafficVolume: 0,
  warningTrend: {
    current: 0,
    direction: 'up',
    value: 0
  },
  deviceTrend: {
    current: 0,
    direction: 'up',
    value: 0
  },
  maintenanceTrend: {
    current: 0,
    direction: 'up',
    value: 0
  },
  trafficTrend: {
    current: 0,
    direction: 'up',
    value: 0
  }
});

// 平台详情
const platformItems = ref<PlatformItemType[]>([]);

// 知识库数据
const knowledgeItems = ref<KnowledgeItemType[]>([]);

// 健康视图模式
const healthViewMode = ref('progress');

// 健康组件数据
const healthComponents = ref([
  { name: '主梁', score: 95, hover: false },
  { name: '桥墩', score: 93, hover: false },
  { name: '桥面', score: 90, hover: false },
  { name: '伸缩缝', score: 85, hover: false },
  { name: '支座', score: 89, hover: false }
]);

// 健康评分等级样式
function getHealthScoreClass(score: number) {
  if (score >= 90) return 'score-excellent';
  if (score >= 75) return 'score-good';
  return 'score-warning';
}

// 传感器数据
const sensorData = ref({
  total: 248,
  online: 243,
  offline: 5,
  warning: 3,
  categories: [
    { name: '应变传感器', online: 62, total: 65, hover: false },
    { name: '振动传感器', online: 58, total: 60, hover: false },
    { name: '位移传感器', online: 55, total: 55, hover: false },
    { name: '倾角传感器', online: 38, total: 38, hover: false },
    { name: '加速度传感器', online: 30, total: 30, hover: false }
  ]
});

// 天气数据
const weatherData = ref({
  location: '舟山大桥区域',
  current: {
    temperature: 28,
    condition: 'sunny',
    humidity: 65,
    windSpeed: 32,
    windDirection: '东南风'
  },
  forecast: [
    { date: '06-01', condition: 'cloudy', tempMax: 32, tempMin: 24, windSpeed: 28 },
    { date: '06-02', condition: 'rainy', tempMax: 26, tempMin: 22, windSpeed: 35 },
    { date: '06-03', condition: 'rainy', tempMax: 25, tempMin: 21, windSpeed: 40 }
  ]
});

// 预警列表
const warningList = ref([
  {
    id: 'W001',
    title: '支座位移预警',
    createTime: new Date(Date.now() - 3600000).toISOString(),
    content: '2号支座位移传感器数值超出预警阈值，当前值：312μm，阈值：300μm',
    type: '位移预警',
    level: 'medium',
    status: '未处理'
  },
  {
    id: 'W002',
    title: '桥墩倾斜预警',
    createTime: new Date(Date.now() - 7200000).toISOString(),
    content: '3号桥墩倾角传感器数值异常，当前值：1.2°，阈值：1.0°',
    type: '倾斜预警',
    level: 'high',
    status: '未处理'
  },
  {
    id: 'W003',
    title: '强风预警',
    createTime: new Date(Date.now() - 1800000).toISOString(),
    content: '预计未来12小时内有8-9级东南风，请注意桥梁安全',
    type: '天气预警',
    level: 'medium',
    status: '处理中'
  },
  {
    id: 'W004',
    title: '车辆超载预警',
    createTime: new Date(Date.now() - 5400000).toISOString(),
    content: '检测到超载车辆，车牌号：浙B12345，轴载：25吨',
    type: '超载预警',
    level: 'high',
    status: '未处理'
  }
]);

// 预警过滤器
const warningFilter = ref('all');

// 预警过滤的结果
const filteredWarnings = computed(() => {
  if (warningFilter.value === 'all') {
    return warningList.value;
  } else if (warningFilter.value === 'high') {
    return warningList.value.filter(item => item.level === 'high');
  } else if (warningFilter.value === 'unhandled') {
    return warningList.value.filter(item => item.status === '未处理');
  }
  return warningList.value;
});

// 预警行样式
function warningRowClassName({ row }) {
  if (row.level === 'high' && row.status === '未处理') {
    return 'warning-row-high';
  } else if (row.status === '未处理') {
    return 'warning-row-unhandled';
  }
  return '';
}

// 设备详情弹窗
const deviceDialog = reactive({
  visible: false,
  title: '',
  data: {
    count: 0,
    status: '',
    lastUpdate: '',
    items: [] as any[]
  }
});

// 预警详情弹窗
const warningDialog = reactive({
  visible: false,
  title: '',
  data: {} as any
});

// 显示设备类型信息
function showDeviceTypeInfo(type: string) {
  let title = '所有设备';
  let status = '全部';
  let deviceItems = [];

  switch (type) {
    case 'online':
      title = '在线设备';
      status = '在线';
      deviceItems = [
        { id: 'D001', name: '振动传感器A01', type: '振动传感器', location: '主梁1号位置', status: '在线' },
        { id: 'D002', name: '应变传感器B03', type: '应变传感器', location: '桥墩2号位置', status: '在线' },
        { id: 'D003', name: '倾角传感器C02', type: '倾角传感器', location: '主塔底部', status: '在线' },
        { id: 'D004', name: '位移传感器D05', type: '位移传感器', location: '伸缩缝3号位置', status: '在线' }
      ];
      break;
    case 'offline':
      title = '离线设备';
      status = '离线';
      deviceItems = [
        { id: 'D023', name: '振动传感器A23', type: '振动传感器', location: '主梁7号位置', status: '离线' },
        { id: 'D045', name: '应变传感器B45', type: '应变传感器', location: '桥墩9号位置', status: '离线' }
      ];
      break;
    case 'warning':
      title = '异常设备';
      status = '异常';
      deviceItems = [
        { id: 'D017', name: '位移传感器D17', type: '位移传感器', location: '支座2号位置', status: '异常' },
        { id: 'D032', name: '振动传感器A32', type: '振动传感器', location: '主梁5号位置', status: '异常' },
        { id: 'D051', name: '应变传感器B51', type: '应变传感器', location: '主塔中部', status: '异常' }
      ];
      break;
    default:
      title = '所有设备';
      deviceItems = [
        { id: 'D001', name: '振动传感器A01', type: '振动传感器', location: '主梁1号位置', status: '在线' },
        { id: 'D017', name: '位移传感器D17', type: '位移传感器', location: '支座2号位置', status: '异常' },
        { id: 'D023', name: '振动传感器A23', type: '振动传感器', location: '主梁7号位置', status: '离线' },
        { id: 'D032', name: '振动传感器A32', type: '振动传感器', location: '主梁5号位置', status: '异常' }
      ];
      break;
  }

  const now = new Date();
  const formattedDate = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');

  deviceDialog.title = title;
  deviceDialog.data = {
    count: deviceItems.length,
    status: status,
    lastUpdate: formattedDate,
    items: deviceItems
  };
  deviceDialog.visible = true;
}

// 处理预警点击
function handleWarningClick(row) {
  warningDialog.title = `预警详情 - ${row.title}`;
  warningDialog.data = { ...row };
  warningDialog.visible = true;
}

// 标记预警为处理中
function handleWarningMark(warning) {
  const index = warningList.value.findIndex(item => item.id === warning.id);
  if (index !== -1) {
    warningList.value[index].status = '处理中';
    warningDialog.data.status = '处理中';
  }
}

// 标记预警为已解决
function handleWarningSolve(warning) {
  const index = warningList.value.findIndex(item => item.id === warning.id);
  if (index !== -1) {
    // 从列表中移除已解决的预警
    warningList.value.splice(index, 1);
    warningDialog.visible = false;
  }
}

// 获取健康评分的颜色
function getHealthColor(score: number) {
  if (score >= 90) return '#67C23A';
  if (score >= 75) return '#E6A23C';
  return '#F56C6C';
}

// 获取预警级别类型
function getWarningLevelType(level: string): 'success' | 'warning' | 'info' | 'danger' | 'primary' {
  switch (level) {
    case 'high':
      return 'danger';
    case 'medium':
      return 'warning';
    case 'low':
      return 'info';
    default:
      return 'info';
  }
}

// 获取预警级别文本
function getWarningLevelText(level: string) {
  switch (level) {
    case 'high':
      return '高';
    case 'medium':
      return '中';
    case 'low':
      return '低';
    default:
      return '';
  }
}

// 格式化时间
function formatTime(dateString: string) {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-');
}

// 获取天气图标
function getWeatherIcon(condition: string) {
  switch (condition) {
    case 'sunny':
      return 'Sunny';
    case 'cloudy':
      return 'Cloudy';
    case 'rainy':
      return 'Lightning';
    default:
      return 'Cloudy';
  }
}

// 获取天气状况文本
function getWeatherConditionText(condition: string) {
  switch (condition) {
    case 'sunny':
      return '晴';
    case 'cloudy':
      return '多云';
    case 'rainy':
      return '雨';
    default:
      return '未知';
  }
}

// 卡片统计悬停效果
function onStatHover(index: number) {
  statsItems.value[index].showPulse = true;
}

function onStatLeave(index: number) {
  statsItems.value[index].showPulse = false;
}

// 模块点击处理
function handleModuleClick(item: any) {
  navigateTo(item.route);
}

// 刷新天气数据
function refreshWeather() {
  fetchWeatherData();
}

// 初始化健康图表
let healthChartInstance: echarts.ECharts | null = null;

function initHealthChart() {
  if (healthViewMode.value !== 'chart') return;

  nextTick(() => {
    const chartDom = document.getElementById('healthChart');
    if (!chartDom) return;

    if (healthChartInstance) {
      healthChartInstance.dispose();
    }

    healthChartInstance = echarts.init(chartDom);

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        max: 100,
        axisLabel: {
          formatter: '{value}分'
        }
      },
      yAxis: {
        type: 'category',
        data: healthComponents.value.map(item => item.name),
        inverse: true
      },
      series: [
        {
          name: '健康评分',
          type: 'bar',
          data: healthComponents.value.map(item => ({
            value: item.score,
            itemStyle: {
              color: getHealthColor(item.score)
            }
          })),
          label: {
            show: true,
            position: 'right',
            formatter: '{c}分'
          }
        }
      ]
    };

    healthChartInstance.setOption(option);
  });
}

// 监听健康视图模式变化
watchEffect(() => {
  if (healthViewMode.value === 'chart') {
    initHealthChart();
  }
});

// 获取统计数据
const fetchStats = async () => {
  try {
    loading.value = true;
    const res = await getDashboardStats();
    if (res.code === 200) {
      statistics.value = res.data;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取平台详情
const fetchPlatformItems = async () => {
  try {
    const res = await getPlatformItems();
    if (res.code === 200) {
      platformItems.value = res.data;
    }
  } catch (error) {
    console.error('获取平台详情失败:', error);
  }
};

// 获取知识库数据
const fetchKnowledgeItems = async () => {
  try {
    const res = await getKnowledgeItems();
    if (res.code === 200) {
      knowledgeItems.value = res.data;
    }
  } catch (error) {
    console.error('获取知识库数据失败:', error);
  }
};

// 获取健康状态数据
const fetchBridgeHealthStatus = async () => {
  try {
    const res = await getBridgeHealthStatus();
    if (res.code === 200) {
      healthComponents.value = res.data.components.map(item => ({
        ...item,
        hover: false
      }));
    }
  } catch (error) {
    console.error('获取桥梁健康状态失败:', error);
  }
};

// 获取传感器状态
const fetchSensorStatus = async () => {
  try {
    const res = await getSensorStatus();
    if (res.code === 200) {
      const data = res.data;
      sensorData.value = {
        ...data,
        categories: data.categories.map(item => ({
          ...item,
          hover: false
        }))
      };
    }
  } catch (error) {
    console.error('获取传感器状态失败:', error);
  }
};

// 获取天气数据
const fetchWeatherData = async () => {
  try {
    const res = await getWeatherData();
    if (res.code === 200) {
      weatherData.value = res.data;
    }
  } catch (error) {
    console.error('获取天气数据失败:', error);
  }
};

// 查看知识库项
function viewKnowledgeItem(item: any) {
  navigateTo(item.url || `/knowledge/${item.id}`);
}

// 导航到指定路径
function navigateTo(path: string) {
  router.push(path);
}

// 窗口大小调整处理
function handleResize() {
  if (healthChartInstance) {
    healthChartInstance.resize();
  }
}

// 定时刷新数据
let refreshTimer: number | null = null;
let timeUpdateTimer: number | null = null;

// 页面加载时获取数据
onMounted(() => {
  fetchStats();
  fetchPlatformItems();
  fetchKnowledgeItems();
  fetchBridgeHealthStatus();
  fetchSensorStatus();
  fetchWeatherData();
  
  // 获取各模块的数量
  fetchUnreadMessageCount();
  fetchUnhandledWarningCount();
  fetchEventCount();

  // 更新时间
  updateCurrentTime();
  timeUpdateTimer = window.setInterval(updateCurrentTime, 1000);

  // 设置数据刷新定时器 - 每60秒刷新一次
  refreshTimer = window.setInterval(() => {
    fetchStats();
    fetchSensorStatus();
    // 定时刷新各模块的数量
    fetchUnreadMessageCount();
    fetchUnhandledWarningCount();
    fetchEventCount();
  }, 60000);

  // 添加窗口调整监听
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清除定时器和监听器
onUnmounted(() => {
  if (refreshTimer !== null) {
    clearInterval(refreshTimer);
  }
  if (timeUpdateTimer !== null) {
    clearInterval(timeUpdateTimer);
  }

  // 清除图表实例
  if (healthChartInstance) {
    healthChartInstance.dispose();
    healthChartInstance = null;
  }

  // 移除窗口调整监听
  window.removeEventListener('resize', handleResize);
});

// 获取未读消息数量
const fetchUnreadMessageCount = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 10000,
      readStatus: 0, // 未读状态
      type: 1 // 预警通知
    };
    const res = await getNoticeList(params);
    if (res && res.total) {
      myModules.value[0].badge = res.total;
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
};

// 获取未处理预警数量
const fetchUnhandledWarningCount = async () => {
  try {
    // 交通事故预警未处理数量
    const trafficParams = {
      pageNum: 1,
      pageSize: 10000,
      status: 0 // 未处理状态
    };
    const trafficRes = await getTrafficAccidentWarningList(trafficParams);
    
    // 环境污染预警未处理数量
    const environmentalRes = await getEnvironmentalPollutionWarningList(trafficParams);
    
    // 地质灾害预警未处理数量
    const geologyRes = await getGeologyWarningList(trafficParams);
    
    // 公共卫生预警未处理数量
    const healthRes = await getPublicHealthWarningList(trafficParams);
    
    // 气象灾害预警未处理数量
    const weatherRes = await getMeteorologicalWarningList(trafficParams);
    
    // 船舶预警未处理数量
    const shipRes = await getShipWarningList(trafficParams);
    
    // 计算总未处理数量
    const totalUnhandled = 
      (trafficRes?.total || 0) + 
      (environmentalRes?.total || 0) + 
      (geologyRes?.total || 0) + 
      (healthRes?.total || 0) + 
      (weatherRes?.total || 0) + 
      (shipRes?.total || 0);
    
    myModules.value[1].badge = totalUnhandled;
  } catch (error) {
    console.error('获取未处理预警数量失败:', error);
  }
};

// 获取事件管理数量
const fetchEventCount = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 10000,
      status: 2 // 进行中的事件
    };
    const res = await getEmergencyEventList(params);
    if (res && res.total) {
      myModules.value[2].badge = res.total;
    }
  } catch (error) {
    console.error('获取事件管理数量失败:', error);
  }
};
</script>

<style scoped lang="scss">
// Base Styles
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
  position: relative;
  overflow-x: hidden;
}

// Header Section
.dashboard-header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
  }

  .left-section {
    .main-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      display: flex;
      align-items: center;

      .greeting {
        color: #409EFF;
        margin-right: 8px;
        font-weight: 500;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: -2px;
          left: 0;
          width: 100%;
          height: 2px;
          background-color: #409EFF;
          transform: scaleX(0);
          transition: transform 0.3s;
          transform-origin: right;
        }
      }

      .platform-name {
        position: relative;
        display: inline-block;

        &::after {
          content: '';
          position: absolute;
          bottom: -2px;
          left: 0;
          width: 100%;
          height: 2px;
          background-color: #409EFF;
          transform: scaleX(0);
          transition: transform 0.3s;
          transform-origin: left;
        }
      }

      &:hover {

        .greeting::after,
        .platform-name::after {
          transform: scaleX(1);
        }
      }
    }

    .subtitle {
      margin: 8px 0 0;
      color: #606266;
      font-size: 14px;
      display: flex;
      align-items: center;

      .subtitle-item {
        position: relative;
        transition: all 0.3s;

        &:hover {
          color: #409EFF;
        }
      }

      .subtitle-separator {
        margin: 0 8px;
        color: #dcdfe6;
      }
    }
  }

  .right-section {
    display: flex;
    align-items: center;

    .current-time {
      margin-right: 24px;
      color: #606266;
      font-size: 14px;
      background-color: #f5f7fa;
      padding: 6px 12px;
      border-radius: 20px;
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 6px;
        color: #909399;
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      padding: 6px 12px;
      border-radius: 20px;
      cursor: pointer;
      position: relative;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      .avatar-wrapper {
        margin-right: 8px;

        .avatar-icon {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          color: #fff;
          background-color: #409EFF;
          padding: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.3s;

          &:hover {
            transform: scale(1.1);
          }
        }
      }

      span {
        color: #606266;
        font-size: 14px;
        margin-right: 4px;
      }

      .expand-icon {
        font-size: 12px;
        color: #909399;
        transition: all 0.3s;
      }

      &:hover .expand-icon {
        transform: rotate(180deg);
      }

      .user-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
        padding: 8px 0;
        min-width: 150px;
        z-index: 10;
        margin-top: 8px;

        &::before {
          content: '';
          position: absolute;
          top: -5px;
          right: 20px;
          width: 10px;
          height: 10px;
          background-color: #fff;
          transform: rotate(45deg);
          box-shadow: -2px -2px 5px rgba(0, 0, 0, 0.05);
        }

        .user-menu-item {
          padding: 8px 16px;
          font-size: 14px;
          color: #606266;
          cursor: pointer;
          transition: all 0.2s;
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 16px;
          }

          &:hover {
            background-color: #f5f7fa;
            color: #409EFF;
          }
        }
      }
    }
  }
}

// Stats Cards
.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;

  .stat-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    transform: translateY(0);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 4px;
      background: linear-gradient(90deg, #409EFF, #67C23A);
      opacity: 0;
      transition: opacity 0.3s;
    }

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);

      &::before {
        opacity: 1;
      }

      .stat-icon {
        transform: scale(1.2);
      }
    }

    &.pulse-animation {
      animation: pulse 1.5s infinite;
    }

    .stat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .stat-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin: 0;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          bottom: -4px;
          left: 0;
          width: 0;
          height: 2px;
          background-color: #409EFF;
          transition: width 0.3s;
        }
      }

      .stat-icon {
        font-size: 20px;
        color: #409EFF;
        background-color: #ecf5ff;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        transition: all 0.3s;
      }
    }

    &:hover .stat-title::after {
      width: 40px;
    }

    .stat-content {
      flex: 1;

      .stat-value {
        font-size: 28px;
        font-weight: 700;
        color: #303133;
        margin-bottom: 8px;
        line-height: 1.2;
      }

      .stat-trend {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 13px;

        span:first-child {
          color: #909399;
        }

        .trend-up {
          color: #67C23A;
          display: flex;
          align-items: center;

          .trend-icon {
            margin-right: 2px;
            font-size: 14px;
          }
        }

        .trend-down {
          color: #F56C6C;
          display: flex;
          align-items: center;

          .trend-icon {
            margin-right: 2px;
            font-size: 14px;
            transform: rotate(180deg);
          }
        }
      }
    }
  }
}

// Transitions
.stats-fade-enter-active,
.stats-fade-leave-active {
  transition: all 0.5s ease;
}

.stats-fade-enter-from,
.stats-fade-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

// Stats card animation
@keyframes pulse {
  0% {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  50% {
    box-shadow: 0 4px 20px rgba(64, 158, 255, 0.3);
  }

  100% {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }
}

// Module Cards
.module-cards {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 30px;

  .module-row {
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
    }

    .module-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 20px;
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        font-size: 20px;
        color: #409EFF;
      }
    }

    .modules-container {
      display: flex;
      flex-wrap: wrap;
      gap: 20px;

      .module-item {
        flex: 1;
        min-width: 110px;
        max-width: 160px;
        padding: 20px 15px;
        text-align: center;
        cursor: pointer;
        border-radius: 12px;
        transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        background-color: #f9fafb;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
        animation: fadeInUp 0.6s;
        position: relative;

        &:hover {
          transform: translateY(-8px);
          box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
        }

        .module-icon {
          display: inline-flex;
          width: 48px;
          height: 48px;
          border-radius: 12px;
          align-items: center;
          justify-content: center;
          margin-bottom: 12px;
          font-size: 24px;
          color: #fff;
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          transition: all 0.3s;

          &.blue {
            background: linear-gradient(135deg, #409EFF, #67C23A);
          }

          &.yellow {
            background: linear-gradient(135deg, #E6A23C, #F56C6C);
          }

          &.green {
            background: linear-gradient(135deg, #67C23A, #409EFF);
          }

          &.red {
            background: linear-gradient(135deg, #F56C6C, #E6A23C);
          }

          &.cyan {
            background: linear-gradient(135deg, #36CFC9, #52C41A);
          }

          &.purple {
            background: linear-gradient(135deg, #9254DE, #409EFF);
          }

          &.orange {
            background: linear-gradient(135deg, #FA8C16, #FAAD14);
          }
        }

        &:hover .module-icon {
          transform: scale(1.1);
        }

        .module-name {
          font-size: 15px;
          color: #303133;
          margin-top: 10px;
          font-weight: 500;
          transition: all 0.3s;
        }

        &:hover .module-name {
          color: #409EFF;
        }

        .module-badge {
          position: absolute;
          top: 10px;
          right: 10px;
          background-color: #F56C6C;
          color: white;
          min-width: 20px;
          height: 20px;
          border-radius: 10px;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 6px;
          box-shadow: 0 2px 4px rgba(245, 108, 108, 0.3);
        }
      }
    }
  }
}

// Content Section
.dashboard-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 30px;

  .content-column {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
}

// Content Cards
.content-card {
  margin-top: -10px;
  background-color: #fff;
  border-radius: 12px;
  padding:5px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  overflow: hidden;

  &:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  }

  &.weather-card {
    background: linear-gradient(to bottom, #f6f9fc, #fff);
  }

  .card-header {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .card-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: #303133;

      .el-icon {
        margin-right: 8px;
        font-size: 18px;
        color: #409EFF;
      }

      .warning-badge {
        margin-left: 8px;
      }
    }

    .card-actions {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .card-content {
    padding: 20px;
  }
}

// Health Indicators
.health-indicators {
  display: flex;
  flex-direction: column;
  gap: 20px;

  .health-component {
    .component-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .component-name {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }

      .component-score {
        font-weight: 600;
        font-size: 14px;

        &.score-excellent {
          color: #67C23A;
        }

        &.score-good {
          color: #E6A23C;
        }

        &.score-warning {
          color: #F56C6C;
        }
      }
    }

    .health-progress {
      transition: all 0.3s;
    }
  }
}

.health-chart {
  .chart-container {
    width: 100%;
    height: 300px;
  }
}

// Warning Table
.warning-title {
  display: flex;
  align-items: center;

  .pulse-icon {
    color: #F56C6C;
    margin-right: 6px;
    animation: pulse-warning 1.5s infinite;
  }
}

.warning-row-high {
  background-color: #fff8f8;
  transition: all 0.3s;

  &:hover {
    background-color: #fff1f1 !important;
  }
}

.warning-row-unhandled {
  background-color: #fdfbf6;

  &:hover {
    background-color: #fbf7ed !important;
  }
}

@keyframes pulse-warning {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

// Device Status
.device-overview {
  margin-bottom: 24px;

  .device-stat {
    text-align: center;
    padding: 15px 10px;
    border-radius: 10px;
    background-color: #f9fafb;
    transition: all 0.3s;
    cursor: pointer;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
    }

    .device-stat-icon {
      margin-bottom: 8px;

      .el-icon {
        font-size: 24px;
        color: #909399;
      }
    }

    .stat-number {
      font-size: 20px;
      font-weight: 700;
      color: #303133;
      margin-bottom: 5px;
    }

    .stat-name {
      font-size: 12px;
      color: #909399;
    }

    &.total {
      .device-stat-icon .el-icon {
        color: #409EFF;
      }
    }

    &.online {
      .device-stat-icon .el-icon {
        color: #67C23A;
      }

      .stat-number {
        color: #67C23A;
      }
    }

    &.offline {
      .device-stat-icon .el-icon {
        color: #909399;
      }

      .stat-number {
        color: #909399;
      }
    }

    &.warning {
      .device-stat-icon .el-icon {
        color: #F56C6C;
      }

      .stat-number {
        color: #F56C6C;
      }
    }
  }
}

.sensor-categories {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .sensor-category {
    .category-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;

      .category-name {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }

      .category-stats-text {
        font-size: 14px;

        .online-count {
          color: #67C23A;
          font-weight: 600;
        }

        .separator {
          color: #909399;
          margin: 0 3px;
        }

        .total-count {
          color: #606266;
        }
      }
    }

    .category-progress-wrapper {
      position: relative;

      .category-progress {
        transition: all 0.3s;
      }
    }
  }
}

.weather-content {
  .current-weather {
    margin-bottom: 24px;

    .weather-location-section {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .location-icon {
        margin-right: 8px;
        color: #409EFF;
        font-size: 18px;
      }

      .weather-location {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .weather-main {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      background-color: #f9fafb;
      border-radius: 12px;
      padding: 16px;

      .weather-icon-temp {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 24px;

        .weather-icon {
          font-size: 48px;
          color: #409EFF;
          margin-bottom: 8px;

          .el-icon {
            font-size: inherit;
          }
        }

        .weather-temp {
          font-size: 36px;
          font-weight: 700;
          color: #303133;
          line-height: 1;

          span {
            font-size: 18px;
            font-weight: 500;
          }
        }
      }

      .weather-condition-details {
        flex: 1;

        .weather-cond {
          font-size: 20px;
          color: #303133;
          font-weight: 600;
          margin-bottom: 12px;
        }

        .weather-details {
          display: flex;
          flex-direction: column;
          gap: 8px;

          .weather-detail {
            display: flex;
            align-items: center;

            .el-icon {
              margin-right: 8px;
              color: #909399;
              font-size: 16px;
            }

            .detail-label {
              color: #909399;
              font-size: 14px;
              margin-right: 8px;
            }

            .detail-value {
              color: #606266;
              font-size: 14px;
              font-weight: 500;
            }
          }
        }
      }
    }
  }

  .weather-forecast {
    display: flex;
    justify-content: space-between;
    background-color: #f9fafb;
    border-radius: 12px;
    padding: 16px;

    .forecast-day {
      text-align: center;
      flex: 1;
      position: relative;

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        right: 0;
        top: 10%;
        height: 80%;
        width: 1px;
        background-color: #ebeef5;
      }

      .forecast-date {
        font-size: 13px;
        color: #606266;
        font-weight: 500;
        margin-bottom: 12px;
      }

      .forecast-icon {
        margin-bottom: 12px;

        .el-icon {
          font-size: 28px;
          color: #409EFF;
        }
      }

      .forecast-temp {
        margin-bottom: 8px;

        .temp-max {
          color: #F56C6C;
          font-size: 15px;
          font-weight: 600;
          margin-right: 6px;
        }

        .temp-min {
          color: #409EFF;
          font-size: 15px;
          font-weight: 600;
        }
      }

      .forecast-wind {
        font-size: 13px;
        color: #909399;
        display: flex;
        align-items: center;
        justify-content: center;

        .el-icon {
          margin-right: 4px;
          font-size: 14px;
        }
      }
    }
  }
}

.knowledge-section {
  margin-top: -10px;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .section-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      margin: 0;
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        color: #409EFF;
      }
    }
  }

  .knowledge-items {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;

    .knowledge-item {
      background-color: #f9fafb;
      padding: 20px;
      border-radius: 12px;
      display: flex;
      align-items: flex-start;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 4px;
        height: 100%;
        background-color: #409EFF;
        transform: scaleY(0);
        transition: transform 0.3s;
        transform-origin: bottom;
      }

      &:hover {
        transform: translateY(-8px) scale(1.02);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);

        &::before {
          transform: scaleY(1);
        }

        .knowledge-icon {
          transform: scale(1.1);
        }
      }

      .knowledge-icon {
        width: 48px;
        height: 48px;
        background-color: #ecf5ff;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        flex-shrink: 0;
        transition: all 0.3s;

        .el-icon {
          font-size: 24px;
          color: #409EFF;
        }
      }

      .knowledge-content {
        flex: 1;

        .knowledge-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          margin: 0 0 10px;
          transition: all 0.3s;
        }

        .knowledge-desc {
          font-size: 14px;
          color: #606266;
          margin: 0;
          line-height: 1.6;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }

      &:hover .knowledge-title {
        color: #409EFF;
      }
    }
  }
}

// Dialogs
.device-dialog-content,
.warning-dialog-content {

  .device-dialog-summary,
  .warning-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f9fafb;
    border-radius: 8px;

    .summary-item,
    .warning-info-item {
      text-align: center;
      padding: 0 10px;

      .summary-label,
      .warning-info-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }

      .summary-value,
      .warning-info-value {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .warning-content {
    margin-top: 16px;

    .warning-content-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .warning-content-value {
      padding: 16px;
      background-color: #f9fafb;
      border-radius: 8px;
      font-size: 14px;
      color: #606266;
      line-height: 1.6;
    }
  }
}

// Animations
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// Media Queries
@media (max-width: 1400px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .knowledge-section .knowledge-items {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 992px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }

  .module-cards .module-row .modules-container {
    justify-content: center;
  }

  .module-cards .module-row .modules-container .module-item {
    flex: 0 0 calc(33.33% - 20px);
    max-width: calc(33.33% - 20px);
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }

  .knowledge-section .knowledge-items {
    grid-template-columns: 1fr;
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;

    .right-section {
      margin-top: 16px;
      width: 100%;
      justify-content: space-between;
    }
  }

  .module-cards .module-row .modules-container .module-item {
    flex: 0 0 calc(50% - 20px);
    max-width: calc(50% - 20px);
  }

  .weather-content .current-weather .weather-main {
    flex-direction: column;

    .weather-icon-temp {
      margin-right: 0;
      margin-bottom: 16px;
    }
  }
}

@media (max-width: 576px) {
  .module-cards .module-row .modules-container .module-item {
    flex: 0 0 calc(100% - 20px);
    max-width: calc(100% - 20px);
  }

  .dashboard-header .right-section {
    flex-direction: column;
    align-items: flex-start;

    .current-time {
      margin-right: 0;
      margin-bottom: 10px;
    }
  }

  .weather-content .weather-forecast {
    flex-wrap: wrap;

    .forecast-day {
      flex: 0 0 50%;
      margin-bottom: 16px;

      &:not(:last-child)::after {
        display: none;
      }
    }
  }
}
</style>